import EventBus from '../../vue2-flow/src/libs/EventBus'
import { AppParams } from '@/utils/appParams'
import Utils from '../../vue2-flow/src/utils/Common'
import FlowRuntimeApi from './FlowRuntimeApi'
import SystemApi from './SystemApi'
import { GlobalParam } from '../GlobalParamApi'
import { Emitter } from "@/utils/Emitter";
import { useFlowStore } from "@/store/modules/flow/flowStore";
import { System } from "@/api/SystemApi";
import { MessageError } from "@/utils";

class AppInitialize {

  constructor () {
    this.FlowStore = useFlowStore()
  }

  /**
   * 监听流程日志
   * @param RES
   * @constructor
   */
  FLOW_LOGGER (RES) {
    EventBus.$emit(AppParams.JAVA_SCRIPT_EVENT.FLOW_LOGGER, RES)
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.FLOW_LOGGER, RES)
  }

  /**
   * 监听节点日志
   * @param RES
   * @constructor
   */
  NODE_LOGGER (RES) {
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_LOGGER, RES)
  }

  /**
   * 监听节点异常事件
   * @param RES
   * @constructor
   */
  NODE_ERROR (RES) {
    EventBus.$emit(AppParams.JAVA_SCRIPT_EVENT.NODE_ERROR)
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_ERROR)
  }

  /**
   * 流程执行结束事件
   * @param FLOW
   * @constructor
   */
  FLOW_COMPLETE (FLOW) {
    const _Flow = this.FlowStore.CurrentFlow
    if (_Flow.id === FLOW.id) {
      _Flow.Detail = FLOW
      this.FlowStore.SetCurrentFlow(_Flow)
    }
    // Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.FLOW_COMPLETE, FLOW)
  }

  /**
   * 节点脚本编程出错
   * @param ERROR
   * @constructor
   */
  NODE_SCRIPT_COMPILE_ERROR (ERROR) {
    EventBus.$emit(AppParams.JAVA_SCRIPT_EVENT.NODE_SCRIPT_COMPILE_ERROR, ERROR)
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_SCRIPT_COMPILE_ERROR, ERROR)
  }

  /**
   * 全局的消息通知
   * @param MESSAGE
   * @constructor
   */
  GLOBAL_MESSAGE_NOTICE (MESSAGE) {
    Utils.MessageWarning(MESSAGE)
  }

  /**
   * 节点开始事件
   * @param NODE
   * @constructor
   */
  NODE_START (NODE) {
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_START, NODE)
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_LOGGER, NODE)
  }

  GLOBAL_PARAM_DATA_UPDATE (GLOBAL) {
    Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.GLOBAL_PARAM_DATA_UPDATE, GLOBAL)
  }

  DEVICE_LOGGER (DeviceErrorResult) {
  }

  /**
   * 监听后台的推送事件
   */
  OnWindow () {
    window.GLOBAL_MESSAGE_NOTICE = this.GLOBAL_MESSAGE_NOTICE
    window.FLOW_LOGGER = this.FLOW_LOGGER
    window.NODE_LOGGER = this.NODE_LOGGER
    window.NODE_ERROR = this.NODE_ERROR
    window.NODE_START = this.NODE_START
    window.DEVICE_LOGGER = (DeviceErrorResult) => Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.DEVICE_LOGGER, DeviceErrorResult)
    return this
  }

  /**
   * 加载配置文件信息
   * @returns {AppInitialize}
   * @constructor
   */
  LoadingSystemConfig () {
    System.GetConfig().then((res) => {
      if (res.IsSuccess) {
        sessionStorage.setItem(AppParams.COMMON.SYSTEM_CONFIG, JSON.stringify(res.Data))
      } else {
        MessageError("系统配置加载失败");
      }
    })
    return this
  }

  /**
   * 加载全局的配置信息
   * @returns {AppInitialize}
   * @constructor
   */
  LoadingGlobalConfig () {
    System.GetGlobalParams().then((res) => {
      Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.APP_CONFIG_COMPLETED)
    })
    return this
  }

  /**
   * 加载所有流程
   * @returns {AppInitialize}
   * @constructor
   */
  LoadingAllFlow () {
    this.FlowStore.SetAllFlow()
    return this
  }

  /**
   * 加载所有设备
   * @returns {AppInitialize}
   * @constructor
   */
  LoadingDevice () {
    this.FlowStore.UpdateDevice()
    return this
  }

  LoadingNodeGroup () {
    this.FlowStore.SetNodeGroup()
    return this
  }

  /**
   * 加载流程的数据结构
   * @returns {AppInitialize}
   * @constructor
   */
  LoadingFlowParamStructure () {
    // this.FlowStore.SetFlowParamStructure()
    return this
  }

  /**
   * 配置加载完成
   * 对外通知一个加载完成事件
   */
  ConfigCompleted () {
    return this
  }

  /**
   * 单次执行
   * @param FlowId 执行流程ID
   * @constructor
   */
  ONCE_RUN (Res = {}) {
    new FlowRuntimeApi().RunFlow(Res.id)
  }

  STOP_PROCESSOR (Flow = {}) {
    new FlowRuntimeApi().StopFlow(Flow.id, (res) => {
      if (res === 'True') {
        Emitter.emit(AppParams.JAVA_SCRIPT_EVENT.NODE_START, {})
      }
    })
  }

  /**
   * 监听内部事件
   */
  OnInternalEvent () {
    Emitter.on(AppParams.JAVA_SCRIPT_EVENT.POST_MESSAGE_BUS, (data) => this.OnPostMessage(data))
    return this
  }

  /**
   * 接收所有消息，合并消息
   *
   * @param Data
   * @constructor
   */
  OnPostMessage (Data) {
    switch (Data.MessageBusType) {
      case AppParams.JAVA_SCRIPT_EVENT.ONCE_RUN:
        this.ONCE_RUN(Data)
        break
      case AppParams.JAVA_SCRIPT_EVENT.STOP_PROCESSOR:
        this.STOP_PROCESSOR(Data)
        break
      case AppParams.JAVA_SCRIPT_EVENT.OPEN_SYSTEM_LOGGER_FORM:
        break
      case AppParams.JAVA_SCRIPT_EVENT.EDIT_VIEW_FLOW:
        new FlowRuntimeApi().OpenForm()
        break;
    }
  }

  /**
   * 注册全局函数，提供给UI编辑时的脚本使用
   * @returns {AppInitialize}
   * @constructor
   */
  RegisterGlobalFunction () {
    window['$SystemApi'] = new SystemApi()
    window['$GlobalParamApi'] = new GlobalParam()
    return this
  }


  /**
   *         NULL,
   *         UPDATE_FLOW_DATA,
   *         UPDATE_EVENT_DATA,
   *         GLOBAL_MESSAGE_NOTICE, // 全局的消息通知
   *         DEVICE_LOGGER,   // 监听设备日志
   *         FLOW_LOGGER,   // 流程日志
   *         FLOW_COMPLETE,  // 流程结束
   *         NODE_ERROR,   // 节点异常
   *         NODE_LOGGER,   // 节点日志
   *         NODE_STATUS,    // 节点状态
   *         NODE_START,  // 节点开始执行
   *         NODE_COMPLETE,  // 节点执行完成
   *         NODE_SCRIPT_COMPILE_ERROR,  // 节点脚本编译出错
   *         GLOBAL_PARAM_DATA_UPDATE,  // 全局变量数据更新
   *         MESSAGE_INFO,  // 消息info
   *         MESSAGE_SUCCESS,  // 消息success
   *         MESSAGE_ERROR,  // 消息error
   *         MESSAGE_WARNING,  // 消息Warning
   * @returns {AppInitialize}
   * @constructor
   */
  MessageForward () {
    const app = window.$vue;
    const Socket = app.config.globalProperties.$Socket;
    if (Socket) {
      Socket.onMessage = (Message) => {
        const Data = JSON.parse(Message)
        Emitter.emit(Data.Type, Data.Data)
        switch (Data.Type) {
          case AppParams.JAVA_SCRIPT_EVENT.NODE_LOGGER:
            if (this.FlowStore.StopLoadingLogger) {
              this.FlowStore.UpdateLogger(Data.Data)
            }
            break;
          case AppParams.JAVA_SCRIPT_EVENT.SYSTEM_NOTIFICATION:
            if (Data.Data === 'REFRESH_PAGE') {
              location.reload();
            }
            break;
          case AppParams.JAVA_SCRIPT_EVENT.FLOW_COMPLETE:
            this.FLOW_COMPLETE(Data.Data)
            break;
          default:
            break
        }
      }
    }

    return this
  }
}

export default AppInitialize
